import asyncio
from queue import Queue
from MyLib.TestToolApi import Debug
from threading import Event
from MyLib.MyServer import AudioSentServer, AudioRecvServer, \
    SocketServer, VideoMainCaptureServer, VideoSubCaptureServer, WebServer


async def socket_server_watcher(
        mainEvent: Event, subEvent: Event,
        audioSentEvent: Event, audioRecvEvent: Event):
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '套接字服务器监听器')
    socketServer = SocketServer(
        qtSAddress=('10.1.0.5', 6711),
        qtRAddress=('10.1.0.4', 6712),
        webSAddress=('0.0.0.0', 8102),
        webRAddress=('0.0.0.0', 8103),
        logging=True
    )
    socketServer.openServer()
    await asyncio.sleep(0)
    debug.pushInfo("监听器启动完成...", "Debug")
    while True:
        if socketServer.isOpened():
            eventDict = socketServer.getEvent()
            if eventDict["main"]:
                mainEvent.set()
            else:
                mainEvent.clear()
            if eventDict["sub"]:
                subEvent.set()
            else:
                subEvent.clear()
            if eventDict["audioSent"]:
                audioSentEvent.set()
            else:
                audioSentEvent.clear()
            if eventDict["audioRecv"]:
                audioRecvEvent.set()
            else:
                audioRecvEvent.clear()
            await asyncio.sleep(0)
        else:
            debug.pushInfo("服务器出现问题!重置中...", "Error")
            socketServer.closeServer()
            socketServer.join()
            socketServer = SocketServer(
                qtSAddress=('10.1.0.5', 6711),
                qtRAddress=('10.1.0.4', 6712),
                webSAddress=('0.0.0.0', 8102),
                webRAddress=('0.0.0.0', 8103),
                logging=True
            )
            socketServer.openServer()
            debug.pushInfo("服务器重启成功!", "Debug")
            await asyncio.sleep(1)


async def video_main_capture_watcher(mainEvent: Event):
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '主视频流服务器监听器')
    videoMainServer = VideoMainCaptureServer(6100)
    videoMainServer.openServer()
    debug.pushInfo("监听器启动完成...", "Debug")
    while True:
        if mainEvent.is_set():
            if videoMainServer.isOpened():
                await asyncio.sleep(0)
            else:
                debug.pushInfo("服务器启动中...", "Debug")
                videoMainServer.closeServer()
                await asyncio.sleep(1)
                videoMainServer = VideoMainCaptureServer(6100)
                videoMainServer.openServer()
                debug.pushInfo("服务器启动成功!", "Debug")
                await asyncio.sleep(1)
        else:
            if videoMainServer.isOpened():
                print(videoMainServer.isOpened())
                debug.pushInfo("客户端退出, 关闭服务器", "Debug")
                videoMainServer.closeServer()
                await asyncio.sleep(1)
            else:
                await asyncio.sleep(0)


async def video_sub_capture_watcher(subEvent: Event):
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '子视频流服务器监听器')
    videoSubServer = VideoSubCaptureServer(6101)
    videoSubServer.openServer()
    debug.pushInfo("监听器启动完成...", "Debug")
    while True:
        if subEvent.is_set():
            if videoSubServer.isOpened():
                await asyncio.sleep(0)
            else:
                debug.pushInfo("服务器启动中...", "Debug")
                videoSubServer.closeServer()
                await asyncio.sleep(1)
                videoSubServer = VideoSubCaptureServer(6101)
                videoSubServer.openServer()
                debug.pushInfo("服务器启动成功!", "Debug")
                await asyncio.sleep(1)
        else:
            if videoSubServer.isOpened():
                debug.pushInfo("客户端退出, 关闭服务器", "Debug")
                videoSubServer.closeServer()
                await asyncio.sleep(1)
            else:
                await asyncio.sleep(0)


async def audio_sent_server_watcher(audioSentEvent: Event):
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '音频流发送服务器监听器')
    audioSentServer = AudioSentServer(6512)
    audioSentServer.openServer()
    debug.pushInfo("监听器启动完成...", "Debug")
    while True:
        if audioSentEvent.is_set():
            if audioSentServer.isOpened():
                await asyncio.sleep(0)
            else:
                debug.pushInfo("服务器启动中...", "Debug")
                audioSentServer.closeServer()
                await asyncio.sleep(1)
                audioSentServer = AudioSentServer(6101)
                audioSentServer.openServer()
                debug.pushInfo("服务器启动成功!", "Debug")
                await asyncio.sleep(1)
        else:
            if audioSentServer.isOpened():
                debug.pushInfo("客户端退出, 关闭服务器", "Debug")
                audioSentServer.closeServer()
                await asyncio.sleep(1)
            else:
                await asyncio.sleep(0)


async def audio_recv_server_watcher(audioRecvEvent: Event):
    debugQueue = Queue(1)
    debug = Debug(debugQueue, True, '音频流接收服务器监听器')
    audioRecvServer = AudioRecvServer(6511)
    audioRecvServer.openServer()
    debug.pushInfo("监听器启动完成...", "Debug")
    while True:
        if audioRecvEvent.is_set():
            if audioRecvServer.isOpened():
                await asyncio.sleep(0)
            else:
                debug.pushInfo("服务器启动中...", "Debug")
                audioRecvServer.closeServer()
                await asyncio.sleep(1)
                audioRecvServer = AudioSentServer(6101)
                audioRecvServer.openServer()
                debug.pushInfo("服务器启动成功!", "Debug")
                await asyncio.sleep(1)
        else:
            if audioRecvServer.isOpened():
                debug.pushInfo("客户端退出, 关闭服务器", "Debug")
                audioRecvServer.closeServer()
                await asyncio.sleep(1)
            else:
                await asyncio.sleep(0)


if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    mainOutEvent = Event()
    subOutEvent = Event()
    audioOutSentEvent = Event()
    audioOutRecvEvent = Event()
    taskSocketServer = loop.create_task(socket_server_watcher(
        mainOutEvent, subOutEvent,
        audioOutSentEvent, audioOutRecvEvent
    ))
    taskMainCapServer = loop.create_task(video_main_capture_watcher(
        mainOutEvent
    ))
    taskSubCapServer = loop.create_task(video_sub_capture_watcher(
        subOutEvent
    ))
    taskAudioSentServer = loop.create_task(audio_sent_server_watcher(
        audioOutSentEvent
    ))
    taskAudioRecvServer = loop.create_task(audio_recv_server_watcher(
        audioOutRecvEvent
    ))


    async def main():
        await asyncio.gather(
            taskSubCapServer, taskMainCapServer, taskSubCapServer,
            taskAudioSentServer, taskAudioRecvServer, loop=loop
        )


    loop.run_until_complete(main())
